package com.example.pclimb.repository;

import android.app.Application;

import androidx.lifecycle.LiveData;

import com.example.pclimb.dao.GuideImageDao;
import com.example.pclimb.database.PclimbDatabase;
import com.example.pclimb.model.GuideImage;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 向导证书图片仓库类
 */
public class GuideImageRepository {

    private GuideImageDao guideImageDao;
    private ExecutorService executorService;

    public GuideImageRepository(Application application) {
        PclimbDatabase database = PclimbDatabase.getInstance(application);
        guideImageDao = database.guideImageDao();
        executorService = Executors.newSingleThreadExecutor();
    }

    /**
     * 插入图片
     */
    public void insert(GuideImage guideImage) {
        executorService.execute(() -> guideImageDao.insert(guideImage));
    }

    /**
     * 删除图片
     */
    public void delete(GuideImage guideImage) {
        executorService.execute(() -> guideImageDao.delete(guideImage));
    }

    /**
     * 获取图片通过ID
     */
    public LiveData<GuideImage> getImageById(int id) {
        return guideImageDao.getImageById(id);
    }

    /**
     * 获取用户的所有证书图片
     */
    public LiveData<List<GuideImage>> getUserImages(int userId) {
        return guideImageDao.getUserImages(userId);
    }

    /**
     * 获取用户的证书图片数量
     */
    public int getUserImageCount(int userId) {
        // 由于需要同步返回结果，使用Runnable并等待结果
        Integer[] result = new Integer[1];
        try {
            executorService.submit(() -> {
                result[0] = guideImageDao.getUserImageCount(userId);
            }).get();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return result[0] != null ? result[0] : 0;
    }

    /**
     * 删除用户的所有证书图片
     */
    public void deleteUserImages(int userId) {
        executorService.execute(() -> guideImageDao.deleteUserImages(userId));
    }
} 